package pri.zjy.concurrent;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zhangjy
 * @description 多线程交替打印
 * <p>
 * Atomic使用，同法三，实际靠volatile控制打印标识flag
 * @date 2025/5/7 21:56
 */
public class AlternatePrint4 {

    static AtomicInteger num = new AtomicInteger(0);

    static int limit = 10;

    static volatile boolean flag = true;

    public static void main(String[] args) {
        Thread thread1 = new Thread() {
            @Override
            public void run() {
                while (num.get() <= limit) {
                    if (flag) {
                        System.out.println(getName() + "---" + num.get());
                        num.getAndIncrement();

                        flag = false;
                    }
                }
            }
        };
        thread1.start();

        Thread thread2 = new Thread() {
            @Override
            public void run() {
                while (num.get() <= limit) {
                    if (!flag) {
                        System.out.println(getName() + "---" + num.get());
                        num.getAndIncrement();

                        flag = true;
                    }
                }
            }
        };
        thread2.start();
    }

}
